#include<stdio.h>
#include<stdlib.h>
#include <string.h>

#define Length 8

#define XALLOC(type,size) (type *)malloc(size*sizeof(type))
#define XMEMSET(pointer,type,size) memset(pointer,0,size*sizeof(type))

int max(int a[])
{
	int i=0;
	int maxNumber = a[0];
	for(i=1;i<Length;i++)
	{
		if(a[i]>maxNumber)
			maxNumber=a[i];
	}
	return maxNumber;
}

void CountingSort(int a[],int b[],int k)
{
	int i,j;
	int *C = XALLOC(int,k);
	XMEMSET(C,int,k);
	
	for(i=0;i<Length;i++)
	{
		C[a[i]]++;
	}

	for(i=1;i<k;i++)
	{
		C[i]+=C[i-1];
	}

	for(j=Length-1;j>=0;j--)
	{
		b[C[a[j]]-1] = a[j]; //Important
		C[a[j]]--;
	}
}

int main() 
{ 
	int a[Length]= {2,5,3,0,2,3,0,3};
	int b[Length];
	XMEMSET(b,int,Length);
	int i=0;
	int k = max(a)+1;

	CountingSort(a,b,k);

	for(i=0;i<Length;i++)
		printf("%d\t",b[i]);

	return 0; 
} 
